package com.smh.demo1.a10;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Proxy;

/**
 * @author shiminghui
 * @date 2025/4/12 16:12
 * @description: TODO
 */
public class JDKProxyDemo {
    /**
     * JDK的代理对象跟目标对象是兄弟关系,他们都实现了同一个接口
     * 所以,Target对象即便是final 的,也可以被代理
     */

    private final static Logger log = LoggerFactory.getLogger(JDKProxyDemo.class);

    public static void main(String[] args) {

        Target target = new Target();

        ClassLoader classLoader = JDKProxyDemo.class.getClassLoader(); //用于获取类加载器,来加载动态生成的代理类(代理类没有字节码文件,所以只能在运行时加载)
        Inter inter = (Inter) Proxy.newProxyInstance(classLoader, new Class[]{Inter.class}, (proxy, method, args1) -> {
            log.info("before.....");
            Object result = method.invoke(target, args1);
            log.info("after.....");
            return result;
        });

        inter.test();

    }

    interface Inter {
        void test();
    }

    // 目标对象
    static class Target implements Inter {
        @Override
        public void test() {
            System.out.println("test");
        }
    }


}
